/*
 * @lc app=leetcode.cn id=110 lang=javascript
 *
 * [110] 平衡二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function (root) {
  if (root === null) return true;

  const getHeight = (root) => {
    if (root === null) return 0;

    // 左子树高度
    let left = getHeight(root.left);
    // 右子树高度
    let right = getHeight(root.right);

    // 高度差超过1，无效的
    if (Math.abs(left - right) > 1) return -1;
    // 左子树或者右子树有无效的
    if (left < 0 || right < 0) return -1;

    // root的高度
    return Math.max(left, right) + 1;
  };

  return getHeight(root) >= 0;
};
// @lc code=end
